import json
from pathlib import Path
from pickle import FALSE
from urllib.request import Request
from src.students import Student
from src.manager import CourseManager
from src.manager import StudentManager
from src.login import login, logout, is_login, LOGIN_USER


class CoursesManagementUI:
    """课程管理二级页面"""

    def __init__(self, courses_manager: CourseManager):
        self.courses_manager = courses_manager

    def query_course(self):
        """查询课程"""
        course_id = input('请输入课程ID>>>:').strip()
        name = input('请输入课程名称>>>:').strip()
        self.courses_manager.query_course(course_id, name)

    def query_all_courses(self):
        """查询所有课程"""
        self.courses_manager.show_courses()

    @is_login
    def add_course(self):
        """添加课程，不是给学生选课"""
        course_name = input('请输入课程名称>>>:').strip()
        credit = int(input('请输入学分>>>:'))
        result = self.courses_manager.add_course(course_name, credit)
        if result['code'] == 800:
            print(result['message'])
        elif result['code'] == 803:
            print(result['message'])
        else:
            print(f'')

    @is_login
    def del_course(self):
        course_code = input('请输入课程代码>>>:').strip()
        result = self.courses_manager.drop_course(course_code)
        if result['code'] == 800:
            print(result['message'])
        elif result['code'] == 804:
            print(result['message'])

    def run(self):
        while True:
            print(f"\n{' 课程管理 ':=^30}")
            print("1. 查看所有课程\n2. 查看单个课程\n3. 新增课程\n4. 删除课程\n  5. 返回上级")
            choice = input("请选择操作: ")

            if choice == '1':
                self.query_all_courses()

            elif choice == '2':
                self.query_course()

            elif choice == '3':
                self.add_course()

            elif choice == '4':
                self.del_course()

            elif choice == '5':
                break
            else:
                print("无效输入，请重新选择")


class StudentManagementUI:
    """学生管理二级页面"""

    def __init__(self, student_manager: StudentManager, courses_manager: CourseManager):
        self.student_manager = student_manager
        self.courses_manager = courses_manager

    @is_login
    def create_students(self):
        """添加学生"""
        name = input('请输入姓名>>>:').strip()
        age = int(input('请输入年龄>>>:'))
        self.student_manager.add_student(name, age)
        print(f'添加学生 {name} 成功')

    @is_login
    def query_students(self):
        """查询所有学生"""
        student_id = input('请输出学生id >>>').strip()
        result = self.student_manager.get_student(student_id)
        # 这里返回的设计不太合理，前端和后端交互的过程中不应该返回对象，因该返回序列后的数据
        # 错误保留下来作为提醒
        if not isinstance(result, Student):
            if result.get('code') == 603:
                print('查询学生信息失败')
                return
        print(f'查询学生信息:::\n {json.dumps(result.to_dict, indent=4, ensure_ascii=False)}')

    def query_student_course(self):
        """查询学生课程"""
        student_id = input('请输出学生id >>>').strip()
        self.student_manager.query_curses(student_id, self.courses_manager.courses)

    def run(self):
        while True:
            print(f"\n{' 学生管理 ':=^30}")
            print("1. 查看所有学生\n2. 添加学生\n3. 查询学生课程\n4. 返回上级")
            choice = input("请选择操作: ")

            if choice == '1':
                self.query_students()

            elif choice == '2':
                self.create_students()

            elif choice == '3':
                self.query_student_course()

            elif choice == '4':
                break

            else:
                print("无效输入，请重新选择")


class MainUi:
    """主界面"""

    root_path = Path(__file__).parent
    __student_data_db = root_path.joinpath('data', StudentManager.students_db)
    __courses_data_db = root_path.joinpath('data', CourseManager.coursers_db)

    def __init__(self):
        self.__current_user = LOGIN_USER
        self.student_manager = StudentManager(self.__student_data_db)
        self.courses_manager = CourseManager(self.__courses_data_db)

    def main(self):
        """主界面"""
        while True:
            print(f"\n{' 学生管理系统 ':=^30}")
            print("1. 登录\n2. 退出登录\n3. 课程管理\n4. 学生管理\n5. 退出系统")

            if self.__current_user:
                print(f"\n当前登录用户: [{self.__current_user}]")

            choice = input("请选择操作: ")

            if choice == '1':
                if not self.__current_user:
                    login()
                else:
                    print("请先退出当前登录")

            elif choice == '2':
                if self.__current_user:
                    logout()
                else:
                    print("尚未登录")

            elif choice == '3':
                if not self.__current_user:
                    CoursesManagementUI(self.courses_manager).run()
                else:
                    print("请先登录")

            elif choice == '4':
                if not self.__current_user:
                    StudentManagementUI(self.student_manager, self.courses_manager).run()
                else:
                    print("请先登录")

            elif choice == '5':
                print("感谢使用，再见！")
                break

            else:
                print("无效输入，请重新选择")


if __name__ == '__main__':
    MainUi().main()
